#include "linkfabric/LinkFabric.hpp"

using namespace linkfabric;

LinkFabric::LinkFabric(MemLink& mem) : mem_(mem) {}

int LinkFabric::openChannel(ChannelPermission perm){
    return mem_.allocChannel(perm);
}

void LinkFabric::freeChannel(int channelId){
    mem_.freeChannel(channelId);
}

bool LinkFabric::send(int ch, const std::vector<TLV>& tlvs) {
    std::vector<uint8_t> out;
    for (auto& tlv : tlvs) {
        auto e = tlv.encode();
        out.insert(out.end(), e.begin(), e.end());
    }
    return mem_.write(ch, out);
}

void LinkFabric::onReceive(int ch, std::function<void(const std::vector<TLV>&)> cb) {
    mem_.onData(ch, [cb](const std::vector<uint8_t>& raw) {
        std::vector<TLV> tlvs;
        size_t off = 0;
        while (off < raw.size()) {
            tlvs.push_back(TLV::decode(raw, off));
        }
        cb(tlvs);
    });
}

void LinkFabric::run() {
    mem_.run();
}